package com.sf.tools.common;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

@SuppressWarnings("unchecked")
public class XMLDateSources {

	public static String filePath = "d:/codeGenerate/db.xml";
	
	
	public static List<String[]> getDataSource() throws Exception{
		List<String[]> sources = new ArrayList<String[]>(0);
		
//		String filePath = "d:/codeGenerate/db.xml";
		File file = new File(filePath);
		if(!file.exists()){
			return sources;
		}
		
		SAXReader reader = new SAXReader();
		Document document = reader.read(filePath);
		
		Element root = document.getRootElement();
		List<Element> dataSource = root.elements();
		for (Element source : dataSource) {
			String[] info = new String[5];

			Attribute attribute = source.attribute("ID");
			System.out.println("ID : " + attribute.getValue());
			info[0] = attribute.getValue();
			for (int i = 0; i < source.nodeCount(); i++) {
				Node node = source.node(i);
				String name = node.getName();
				if("TYPE".equals(name)){
					String text = node.getText();
					System.out.println(name + " - " + text);
					info[1] = text;
				}else if("URL".equals(name)){
					String text = node.getText();
					System.out.println(name + " - " + text);
					info[2] = text;
				}else if("USERNAME".equals(name)){
					String text = node.getText();
					System.out.println(name + " - " + text);
					info[3] = text;
				}else if("PASSWORD".equals(name)){
					String text = node.getText();
					System.out.println(name + " - " + text);
					info[4] = text;
				}
			}
			System.out.println("*************");
			
			sources.add(info);
		}
		
		return sources;
	}
	
	private static boolean exists(String urlConn, String user) throws Exception{
		List<String[]> list = getDataSource();
		for (String[] info : list) {
			if(info[2].equals(urlConn) && info[3].equals(user)){
				return true;
			}
		}
		return false;
	}
	public static boolean add(String dbType, String urlConn, String user, String pass) throws Exception {
		boolean exists = exists(urlConn,user);
		if(exists){
			return false;
		}
//		String filePath = "d://1111//db.xml";
		File file = new File(filePath);
		if(!file.exists()){
			file.getParentFile().mkdirs();
			Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"UTF-8"));
			StringBuffer sb = new StringBuffer();
			sb.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>").append("\n")
			  .append("<DATASOURCE>").append("\n")
			  .append("</DATASOURCE>");
			out.write(sb.toString());
			out.close();
		}
		
		SAXReader reader = new SAXReader();
		Document document = reader.read(filePath);
		
		Element root = document.getRootElement();
		List<Element> list = root.elements();
		
		Element source = DocumentHelper.createElement("SOURCE");
		source.addAttribute("ID", list.size()+1+"");
		List<Element> sources = source.elements();
		Element type = DocumentHelper.createElement("TYPE");
		type.setText(dbType);
		Element url = DocumentHelper.createElement("URL");
		url.setText(urlConn);
		Element username = DocumentHelper.createElement("USERNAME");
		username.setText(user);
		Element password = DocumentHelper.createElement("PASSWORD");
		password.setText(pass);
		sources.add(sources.size(),type);
		sources.add(sources.size(),url);
		sources.add(sources.size(),username);
		sources.add(sources.size(),password);
		list.add(list.size(),source);
		
		OutputFormat former = OutputFormat.createPrettyPrint();
		
		former.setEncoding("utf-8");
		
		XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(filePath),"utf-8"),former);
		writer.write(document);
		writer.close();
		
		return true;
	}
	
	public static void delete(String id) throws Exception {
//		String filePath = "d://1111//db.xml";
		File file = new File(filePath);
		if(!file.exists()){
			return ;
		}
		
		SAXReader reader = new SAXReader();
		Document document = reader.read(filePath);
		
		Element root = document.getRootElement();
		List<Element> dataSource = root.elements();
		for (Element source : dataSource) {
			Attribute attribute = source.attribute("ID");
			System.out.println("ID : " + attribute.getValue());
			if(!id.equals(attribute.getValue())){
				continue;
			}
			
			for (int i = 0; i < source.nodeCount(); i++) {
				Node node = source.node(i);
				String name = node.getName();
				if("TYPE".equals(name)){
					String text = node.getText();
					System.out.println(name + " - " + text);
				}else if("URL".equals(name)){
					String text = node.getText();
					System.out.println(name + " - " + text);
				}else if("USERNAME".equals(name)){
					String text = node.getText();
					System.out.println(name + " - " + text);
				}else if("PASSWORD".equals(name)){
					String text = node.getText();
					System.out.println(name + " - " + text);
				}
			}
			System.out.println("*************");
			root.remove(source);
			
			OutputFormat former = OutputFormat.createPrettyPrint();
			
			former.setEncoding("utf-8");
			
			XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(filePath),"utf-8"),former);
			writer.write(document);
			writer.close();
		}
	}
	
	public static void main(String[] args) throws Exception {
//		add();
//		delete("1");
		getDataSource();
	}
}
